//
//  DownLoad.m
//  downdemo
//
//  Created by 陶秋安 on 16/3/3.
//  Copyright © 2016年 孙智慧. All rights reserved.
//

#import "DownLoad.h"
#import "DownloadProess.h"

@implementation DownLoad

-(id)init
{
    if(self=[super init])
    {
        
    }
    return self;
}
 -(void) setDel:(id<DownloadDelegate>)delegate
{
    _delegate= delegate;
}

- (void) setDeleteDel:( id<DownloadDelDelegate>)delegate
{
    _delDelegate= delegate;
}

-(id)init:(NSString *)fileURL andStorePath:(NSString *)storePath
{
    if(self=[super init])
    {
               _fileURL=fileURL;
        _storePath= storePath;
    }
    return self;
}

- (void) ddLoad
{
    NSURLSessionConfiguration * config=[NSURLSessionConfiguration defaultSessionConfiguration];
    
    _session=[NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
    
    NSURL *url=[NSURL URLWithString:_fileURL];
    
    _request=[NSURLRequest requestWithURL:url];
    
    _task= [_session downloadTaskWithRequest:_request];
    
    NSLog(@"开始加载");
    
    [_task resume];
}

- (void) pause
{
    //暂停
    NSLog(@"暂停下载");
    
    [_task cancelByProducingResumeData:^(NSData *resumeData)
     {
         _data=resumeData;
     }];
    
    _task=nil;
}
- (void) resume
{
    //恢复
    NSLog(@"恢复下载");
    
    if(!_data)
    {
        NSURL *url=[NSURL URLWithString:_fileURL];
        
        _request=[NSURLRequest requestWithURL:url];
        
        _task=[_session downloadTaskWithRequest:_request];
        
    }
    else
    {
        _task=[_session downloadTaskWithResumeData:_data];
    }
    
    [_task resume];
}


- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    NSURL * url=[NSURL fileURLWithPath:_storePath];
    
    NSFileManager * manager=[NSFileManager defaultManager];
    
    [manager moveItemAtURL:location toURL:url error:nil];
    
    if(_delDelegate!=nil)
    {
        [_delDelegate del:self];
    }
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    CGFloat progress=(totalBytesWritten*1.0)/totalBytesExpectedToWrite;
    DownloadProess *download=[[DownloadProess alloc]init];
    [download setPro:progress];
    if(_delegate!=nil)
    {
        [_delegate setProgess:progress];
    }
}

@end
